package cn.iocoder.yudao.core.thread.config;

import cn.iocoder.yudao.core.thread.core.utils.FutureUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {

        int core = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                core * 10,
                core * 15,
                5,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(5000),
                new CustomizableThreadFactory("eternity-pool-"),
                new ThreadPoolExecutor.CallerRunsPolicy());
        FutureUtils.setThreadPoolExecutor(threadPoolExecutor);

        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            log.info("ThreadPoolExecutor closing ...");
            threadPoolExecutor.shutdown();
            log.info("ThreadPoolExecutor closed");
        }));
        return threadPoolExecutor;

    }
}
